﻿using System;

using System.Linq;
using System.Net.Http.Headers;
using System.Net.Http;
using System.Net;
using System.Security.Claims;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Web.Http;
using System.Web;
using System.Web.Http.Filters;
using System.Web.Http.Controllers;
using System.Web.UI.WebControls;
using Microsoft.Ajax.Utilities;
using Newtonsoft.Json;
using wnet.admin.wentcommon;


public class JwtAuthenticationFilter : Attribute, IAuthenticationFilter
{
    public bool AllowMultiple => false;

    public Task AuthenticateAsync(HttpAuthenticationContext context, CancellationToken cancellationToken)
    {
        var request = context.Request;
        var headers = request.Headers;

        // 从HTTP头中获取JWT令牌
        var authHeader = headers.Authorization;
        if (authHeader != null && authHeader.Scheme == "Bearer")
        {
            var jwtToken = authHeader.Parameter;

            // 验证JWT令牌
            try
            {
                //var str = JwtHelp.GetJwtDecode(jwtToken);

                // 验证成功，不需要继续执行其他的过滤器

                return Task.FromResult(0);
            }
            catch
            {
                // 令牌验证失败，抛出未授权异常

                var task = Task.FromResult(0);
                return task;
            }
        }


        // 如果没有提供有效的JWT令牌，则抛出未授权异常
        var response = context.Request.CreateResponse(HttpStatusCode.BadRequest);

        var errordata = new { code = 401, msg = "请重新登入", data = new { } };

        response.Content = new StringContent(JsonConvert.SerializeObject(errordata), Encoding.UTF8, "application/json");
        throw new HttpResponseException(response);

    }

    public Task ChallengeAsync(HttpAuthenticationChallengeContext context, CancellationToken cancellationToken)
    {
        context.Result = new AddChallengeOnUnauthorizedResult("JWT", context.Result);
        return Task.FromResult(0);
    }

    public void OnAuthenticationChallenge(HttpAuthenticationChallengeContext context)
    {
        context.Result = new AddChallengeOnUnauthorizedResult("JWT", context.Result);
    }
}

public class AddChallengeOnUnauthorizedResult : IHttpActionResult
{
    string _realm;
    IHttpActionResult _innerResult;

    public AddChallengeOnUnauthorizedResult(string realm, IHttpActionResult innerResult)
    {
        _realm = realm;
        _innerResult = innerResult;
    }

    public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
    {
        var response = _innerResult.ExecuteAsync(cancellationToken).Result;

        if (response.StatusCode == HttpStatusCode.Unauthorized)
        {
            response.Headers.WwwAuthenticate.Add(new AuthenticationHeaderValue("Bearer", _realm));
        }

        return Task.FromResult(response);
    }
}